package controllers;

import java.util.HashMap;
import java.util.Map;

import spark.Request;
import spark.Response;

import models.*;
import data.TaskDAO;

public class TaskController extends BaseController {
	
	private TaskDAO dao;
	
	public TaskController(Request request, Response response) {		
		super(request, response);
		dao = new TaskDAO();
	}

	public Object hello() {
		Map<String, Object> attributes = new HashMap<>();
		attributes.put("message", "Viet Thanh");
		return render(attributes, "task/hello.html");
	}
	
	public Object list() {
		Map<String, Object> attributes = new HashMap<>();
		try{
		
		attributes.put("tasks", dao.list());
		}catch(Exception e) {
			attributes.put("error", e.fillInStackTrace().getMessage());
			e.printStackTrace();
			e.fillInStackTrace().getMessage();
			return render(attributes, "error.html");
		}
		return render(attributes, "task/list.html");
	}
	
	public Object add() {
		if(request.requestMethod().toUpperCase().equals("GET")){
			Map<String, Object> attributes = new HashMap<>();
			attributes.put("task", new Task());
			return render(attributes, "task/add.html");
		}else {
			String name = request.queryParams("name");
			String description = request.queryParams("description");
			dao.insert(name, description);
			response.status(201);
			redirect("tasks");
			return "";
		}
	}

	public Object delete() {
		int id = Integer.parseInt( request.params(":id"));
		dao.delete(id);
		redirect("tasks");
		return "";
	}

	public Object edit() {
		int id = Integer.parseInt( request.params(":id"));
		Map<String, Object> attributes = new HashMap<>();
		if(request.requestMethod().toUpperCase().equals("GET")){
			attributes.put("task", dao.get(id));
			return render(attributes, "task/edit.html");
		}else {
			String name = request.queryParams("name");
			String description = request.queryParams("description");
			dao.update(id, name, description);
			redirect("tasks");
			return "";
		}
	}
	
}